package StackAndQueuePackage;

import org.junit.jupiter.api.Test;

import java.util.Stack;

/**
 * @author Lzm
 * @version 1.0
 */
public class removeDuplicates_ {

  @Test
  public void removeDuplicatesTest(){
    String s = "abbaca";
    System.out.println(removeDuplicates(s));
  }

  public String removeDuplicates(String s) {
    if (s == null || s.equals("")){
      return null;
    }
    StringBuffer sb = new StringBuffer();
    Stack<Character> stack = new Stack<>();
    stack.push(s.charAt(0));

    char[] chars = s.toCharArray();
    for (int i = 1 ; i < chars.length ; i++){
      if (!stack.isEmpty() && chars[i] == stack.peek() ){
        stack.pop();
      }
      else{
        stack.push(chars[i]);
      }
    }
    while(!stack.isEmpty()){
      sb.append(stack.pop());
    }
    return sb.reverse().toString();
  }
  public String removeDuplicates2(String s) {
    if (s == null || s.equals("")){
      return null;
    }
    int fast = 0;
    int slow = 0;
    char[] chars = s.toCharArray();
    for (fast = 0 ; fast < chars.length ; fast++){
      chars[slow] = chars[fast];
      if (chars[slow] == chars[slow - 1]){
        slow--;
      }
      else{
        slow++;
      }
    }
    return new String(chars,0,slow);
  }
}
